package com.project.lk.nurseapp.common.view.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.ToastUtils;

import java.util.List;
import java.util.UUID;

/**
 * 功能介绍：这是封装好的蓝牙管理模块，可以直接调用
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class BleManager {

    static BleManager mManager;
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED = "com.project.lk.nurseapp.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.project.lk.nurseapp.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.project.lk.nurseapp.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.project.lk.nurseapp.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "com.project.lk.nurseapp.le.EXTRA_DATA";
    public final static String EXTRA_DATA_BYTE = "com.project.lk.nurseapp.le.EXTRA_DATA_BYTE";
    public final static UUID UUID_HEART_RATE_MEASUREMENT = UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
    private final static String TAG = "MLOG";

    //利用单例模式获取BleManager的对象
    public static BleManager init() {

        if (mManager == null) {
            synchronized (BleManager.class) {
                mManager = new BleManager();
            }
        }
        return mManager;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) BaseApp.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }


    /*蓝牙回调方法*/
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            Log.e("MLOG", "onCharacteristicRead");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            Log.e("MLOG", "onCharacteristicChanged");
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    };

    /*连接成功回调*/
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        BaseApp.getContext().sendBroadcast(intent);
    }

    /*有数据成功回调*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);

        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, stringBuilder.toString());
            intent.putExtra(EXTRA_DATA_BYTE,data);
        }
        BaseApp.getContext().sendBroadcast(intent);
    }


    //发送数据给ble设备
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void sendByte(byte[] bytes) {
        if (mBluetoothGatt != null) {
            BluetoothGattService service = mBluetoothGatt
                    .getService(StarConstants.SERVICE_ID);
            BluetoothGattCharacteristic ale = service.getCharacteristic(StarConstants.ACC_MEASUREMENT_CHARAC2);
            boolean set = mBluetoothGatt.setCharacteristicNotification(ale, true);
            Log.d(TAG, " setnotification = " + set);
            ale.setValue(bytes);
            mBluetoothGatt.writeCharacteristic(ale);
            BluetoothGattCharacteristic mHRMcharac = service.getCharacteristic(StarConstants.WEITE_ID);
            mBluetoothGatt.setCharacteristicNotification(mHRMcharac, true);
            setCharacteristicNotification(mHRMcharac, true);
        } else {
            ToastUtils.showShortToast("请重新启动蓝牙");
        }

    }
    //发送数据给ble设备
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void sendByte(byte[] bytes,UUID serviceId,UUID readId,UUID writeId) {
        try{
            if (mBluetoothGatt != null) {
                BluetoothGattService service = mBluetoothGatt
                        .getService(serviceId);
                BluetoothGattCharacteristic ale = service.getCharacteristic(readId);
                boolean set = mBluetoothGatt.setCharacteristicNotification(ale, true);
                Log.d(TAG, " setnotification = " + set);
                ale.setValue(bytes);
                mBluetoothGatt.writeCharacteristic(ale);
                BluetoothGattCharacteristic mHRMcharac = service.getCharacteristic(writeId);
                mBluetoothGatt.setCharacteristicNotification(mHRMcharac, true);
                setCharacteristicNotification(mHRMcharac, true);
            } else {
                ToastUtils.showShortToast("请重新启动蓝牙");
            }
        }catch (Exception e){
            ToastUtils.showShortToast("发送指令失败");

        }


    }

    /*连接ble设备*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public boolean connect(final String address) {

        boolean flag = false;
        if ((address != null)) {
            flag = true;
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                Log.w("MLOG", "DeviceModel not found.  Unable to connect.");
                return false;
            }
            mBluetoothGatt = device.connectGatt(BaseApp.getContext(), false, mGattCallback);
            mBluetoothDeviceAddress = address;
            mConnectionState = STATE_CONNECTING;
            return flag;
        }
        return flag;
    }

    /*断开ble连接*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     * 关闭释放资源
     */

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }

        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        if (StarConstants.WEITE_ID.equals(characteristic.getUuid())
                ||StarConstants.BABY_VOICE_WEITE_ID.equals(characteristic.getUuid())
                ||StarConstants.NEW_SPHY_READ_ID.equals(characteristic.getUuid())) {
            Log.e("MLOG","WEITE_ID");
            // This is specific to Heart Rate Measurement.
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
        }
//        else if (StarConstants.NEW_SPHY_READ_ID.equals(characteristic.getUuid())){
//            Log.e("MLOG","NEW_ID");
//            // This is specific to Heart Rate Measurement.
//            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
//                    UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
//            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//            mBluetoothGatt.writeDescriptor(descriptor);
//        }
    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices();
    }

    /*刷新通知，从而获取ble传来的数据*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void initNotify() {
        if (mBluetoothGatt != null) {
            try {
                BluetoothGattService servicie = mBluetoothGatt.getService(StarConstants.SERVICE_ID);
                if (servicie != null) {
                    BluetoothGattCharacteristic characteristic = servicie.getCharacteristic(StarConstants.WEITE_ID);
                    mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(StarConstants.WEITE_ID);
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                    return;
                }
            } catch (Exception localException1) {
            }

        }
    }

    /*刷新通知，从而获取ble传来的数据*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void initNotify(UUID serviceId,UUID readId,UUID writeId ) {
        if (mBluetoothGatt != null) {
            try {
                BluetoothGattService servicie = mBluetoothGatt.getService(serviceId);
                if (servicie != null) {
                    BluetoothGattCharacteristic characteristic = servicie.getCharacteristic(writeId);
                    mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(readId);
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                    return;
                }
            } catch (Exception localException1) {
            }

        }
    }



    public int getmConnectionState() {
        return mConnectionState;
    }

    public String getConnAddress() {
        return mBluetoothDeviceAddress;
    }

    public void disableBlueBle(String type) {
        SharedPreferencesUtils.setParam(type, false);
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.disable();
        }
    }

    /*判断蓝牙是否打开*/
    public boolean isOpenBleTooth() {
        return mBluetoothAdapter.enable();
    }


}
